//
//  ShopViewController.m
//  TTFriend
//
//  Created by 李正兵 on 2019/5/5.
//  Copyright © 2019 李正兵. All rights reserved.
//

#import "ShopViewController.h"
#import "TTSCollectionConfig.h"
#import "SVProgressHUD.h"
#import "HomeASProductItem.h"

@interface ShopViewController (){
    CGFloat lastPosition;
}

@property (nonatomic, strong) UICollectionViewLayout *layout;

@end

@implementation ShopViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.usePullReload = YES;
        _autoReloadCell = YES;
        _useAS = YES;
        self.listType = ListTypeHome;
        
    }
    return self;
}

- (void)loadView {
    [super loadView];
    self.usePullReload = YES;
    _autoReloadCell = YES;
    _useAS = YES;
    self.listType = ListTypeHome;
    
    if (!_useAS) {
        if (!_collectionView) {
            [self initCollectionLayout];
            _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:_layout ];
            _collectionView.frame = self.view.bounds;
            if ([self.collectionView respondsToSelector:@selector(setPrefetchingEnabled:)]) {
                _collectionView.prefetchingEnabled = NO;
            }
            _collectionView.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:_collectionView];
        }
    }else {
        if (!_asCollectionNode) {
            [self initCollectionLayout];
            _asCollectionNode = [[ASCollectionNode alloc]initWithFrame:self.view.bounds collectionViewLayout:_layout];
            _asCollectionNode.frame = self.view.bounds;
            _asCollectionNode.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            _asCollectionNode.backgroundColor = [UIColor clearColor];
            [self.view addSubnode:_asCollectionNode];
        }
    }
    
}

- (void)initCollectionLayout {
    _layout = [[UICollectionViewFlowLayout alloc]init];
}

- (void)createDataSource {
    
    
    Class class = [[TTSCollectionConfig sharedInstance] dataSourceByListType:self.listType];
    
    if(_useAS) {
        self.dataSource = [[class alloc]initWithASCollectionView:self.asCollectionNode
                                                        listType:self.listType
                                                        delegate:self];
    }else {
        self.dataSource = [[class alloc]initWithCollectionView:self.collectionView
                                                      listType:self.listType
                                                      delegate:self];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.view.backgroundColor = HEX_COLOR(0xf1f1f1);
    [self createDataSource];
    
    [SVProgressHUD showInfoWithStatus:@"正在加载.."];
}

- (BOOL)showPullRefresh {
    return _usePullReload;
}


- (void)registerCell:(Class)className {
    NSString *itemName = NSStringFromClass(className);
    NSString *cellName = [NSString stringWithFormat:@"%@Cell",itemName];
    Class cellClass = NSClassFromString(cellName);
    [_collectionView registerClass:cellClass forCellWithReuseIdentifier:[NSString stringWithFormat:@"TTSCollectionViewManager_%@iCell", className]];
    
}

- (void)registerSupplementaryView:(Class)className {
    NSString *itemName = NSStringFromClass(className);
    NSString *cellName = [NSString stringWithFormat:@"%@View",itemName];
    Class cellClass = NSClassFromString(cellName);
    if(!_useAS) {
        [_collectionView registerClass:cellClass forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:[NSString stringWithFormat:@"TTSCollectionViewManager_%@iView", className]];
    }else {
        [_asCollectionNode registerSupplementaryNodeOfKind:cellName];
    }
}

- (void)registerSupplementaryView:(Class)className kind:(NSString *)kind{
    NSString *itemName = NSStringFromClass(className);
    NSString *cellName = [NSString stringWithFormat:@"%@View",itemName];
    Class cellClass = NSClassFromString(cellName);
    if(!_useAS) {
        [_collectionView registerClass:cellClass forSupplementaryViewOfKind:kind withReuseIdentifier:[NSString stringWithFormat:@"TTSCollectionViewManager_%@iView", className]];
    }else {
        [_asCollectionNode registerSupplementaryNodeOfKind:cellName];
    }
}

- (void)dealloc {
    [self.dataSource stopLoading];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (animated) {
        //        [self.tableView flashScrollIndicators];
    }
    if (self.listType) {
        [self startLoadData];
    }
    if (self.autoReloadCell) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:kBBReloadCellNotification object:nil];
    }
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.title = @"商城";
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(autoReload:)
                                                 name:kBBAutoLoadNotification
                                               object:nil];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kBBAutoLoadNotification
                                                  object:nil];
    
    if (self.autoReloadCell) {
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(reloadCell:)
                                                     name:kBBReloadCellNotification
                                                   object:nil];
    }
    
    
    
}

- (void)autoReload:(NSNotification *)notification {
    _loaded = NO;
    [self startLoadData];
}

- (void)scrollCollectionViewToSearchBarAnimated:(BOOL)animated {
    NSAssert(YES, @"This method should be handled by a subclass!");
}



- (void)startLoadData {
    if (!_loaded) {
        [self.dataSource startLoading:NO params:self.requestParams];
        _loaded = YES;
    }
}


- (void)reloadData {
    [self.dataSource reloadCollectionViewData:YES];
}

- (void)reloadCell:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    if (userInfo) {
        NSInteger actionType = [[userInfo objectForKey:@"type"] integerValue];
        NSString *dataId = [userInfo objectForKey:@"dataId"];
        [self.dataSource refreshCell:actionType dataId:dataId];
    }
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}

- (void)didFinishLoad:(TTSDataLoadPolicy)loadPolicy error:(NSError *)error {
    NSLog(@"%s",__func__);
    [SVProgressHUD dismiss];
    
}

- (void)actionItemClick:(id)item {
    HomeASProductItem *productItem = (HomeASProductItem*)item;
    HomeProductListModel *model = productItem.model;
    if (model.im) {
        NSString *telNum = [NSString stringWithFormat:@"tel://%@",model.im];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:telNum]];
    }
}

@end
